﻿using System;
using System.IO;
using System.Linq;
using Microsoft.Samples.ServiceHosting.StorageClient;
using WASM.WebSite.DataEntities;

namespace WASM.WebSite.Models
{
	public class BlobRepository
	{
		BlobStorage _blobStorage = null;

		public BlobRepository(string storageUri, string accountName, string key)
		{
			_blobStorage = BlobStorage.Create(new Uri(storageUri), null, accountName, key);
		}

		public static BlobRepository Create(Guid azureStorageId)
		{
			AzureStorage azureStorage = AzureStorageUserSettingsRepository.Single(azureStorageId);
			return new BlobRepository(azureStorage.asUrl, azureStorage.asAccountName, azureStorage.asKey);
		}

		public BlobContainer[] ListOfContainers()
		{
			return _blobStorage.ListBlobContainers().ToArray();
		}

		public BlobProperties[] ListOfBlobs(string contaiberName)
		{
			BlobContainer blobContainer = GetContainer(contaiberName);
			return blobContainer.ListBlobs(null, true).OfType<BlobProperties>().ToArray();
		}

		public byte[] LoadBlobContent(string containerName, string blobName, out BlobProperties blobProperties)
		{
			BlobContainer blobContainer = GetContainer(containerName);

			MemoryStream ms = new MemoryStream();
			BlobContents blobContents = new BlobContents(ms);
			blobProperties = blobContainer.GetBlob(blobName, blobContents, true);
			return blobContents.AsBytes();
		}

		public void Delete(string containerName, string blobName)
		{
			BlobContainer blobContainer = GetContainer(containerName);
			blobContainer.DeleteBlob(blobName);
		}

		public void Delete(string containerName)
		{
			BlobContainer blobContainer = GetContainer(containerName);
			blobContainer.DeleteContainer();
		}

		public void UploadBlobContent(string containerName, string blobName, byte[] content)
		{
			BlobContainer blobContainer = GetContainer(containerName);
			blobContainer.CreateBlob(new BlobProperties(blobName), new BlobContents(content), true);
		}

		public void Create(string containerName, bool isPrivate)
		{
			BlobContainer blobContainer = GetContainer(containerName);
			blobContainer.CreateContainer(null, isPrivate ? ContainerAccessControl.Private : ContainerAccessControl.Public);
		}

		public bool IsContainerExist(string containerName)
		{
			return GetContainer(containerName).DoesContainerExist();
		}

		public bool IsContainerPrivate(string containerName)
		{
			BlobContainer blobContainer = GetContainer(containerName);
			return blobContainer.GetContainerAccessControl() == ContainerAccessControl.Private;
		}

		private BlobContainer GetContainer(string contaiberName)
		{
			return _blobStorage.GetBlobContainer(contaiberName);
		}
	}
}
